/**
 * created by yangtong on 2025/6/14 下午5:22
 * 加深或淡化颜色（16进制，eg：#FFF）
 */
export const mixHexWithWhite = (hex: string, ratio = 0.75) => {
    let color = hex.replace('#', '')
    if (color.length === 3) {
        color = color.split('').map(c => c + c).join('')
    }
    const r = parseInt(color.slice(0, 2), 16)
    const g = parseInt(color.slice(2, 4), 16)
    const b = parseInt(color.slice(4, 6), 16)
    // 混合白色
    const mixedR = Math.round(r + (255 - r) * ratio)
    const mixedG = Math.round(g + (255 - g) * ratio)
    const mixedB = Math.round(b + (255 - b) * ratio)
    return `rgb(${mixedR},${mixedG},${mixedB})`
}

/**
 * 将十六进制颜色转换为 RGB
 */
export const hexToRgb = (hex: string): { r: number; g: number; b: number } | null => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null
}

/**
 * 将 RGB 转换为十六进制
 */
export const rgbToHex = (r: number, g: number, b: number): string => {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
}

/**
 * 生成带透明度的颜色
 */
export const addAlpha = (color: string, alpha: number): string => {
    const rgb = hexToRgb(color)
    if (!rgb) return color
    return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`
}

/**
 * 调整颜色亮度
 * @param color 十六进制颜色
 * @param percent 百分比 (正数变亮，负数变暗)
 */
export const adjustBrightness = (color: string, percent: number): string => {
    const rgb = hexToRgb(color)
    if (!rgb) return color

    const amount = Math.round(2.55 * percent)
    const r = Math.max(0, Math.min(255, rgb.r + amount))
    const g = Math.max(0, Math.min(255, rgb.g + amount))
    const b = Math.max(0, Math.min(255, rgb.b + amount))

    return rgbToHex(r, g, b)
}

export const normalizeValue = (val: string | number | null | undefined): string => {
    if (val === null || val === undefined) return ''
    return String(val)
}